package com.chj.design.sk;

import java.util.ArrayList;
import java.util.List;

public class Code03_Observer2 {
	public interface Observer {
		/**
		 * 更新
		 *
		 * @param msg 通知的信息
		 */
		void update(String msg);
	}

	public static class ConcreteObserver implements Observer {
		private static final String TAG = "ConcreteObserver";
		private String name;

		public ConcreteObserver(String name) {
			this.name = name;
		}

		@Override
		public void update(String msg) {
			System.out.println(TAG + "update: my name is " + name + "--" + msg);
		}
	}

	public interface Subject {
		/**
		 * 添加观察者
		 *
		 * @param observer 观察者
		 */
		public void attach(Observer observer);

		/**
		 * 删除观察者
		 *
		 * @param observer 观察者
		 */
		public void detach(Observer observer);

		/**
		 * 通知观察者
		 *
		 * @param msg 通知的信息
		 */
		public void notify(String msg);
	}

	public static class ConcreteSubject implements Subject {

		/**
		 * 存储观察者的集合
		 */
		private List<Observer> mObserverList = new ArrayList<>();

		@Override
		public void attach(Observer observer) {
			mObserverList.add(observer);
		}

		@Override
		public void detach(Observer observer) {
			mObserverList.remove(observer);
		}

		@Override
		public void notify(String msg) {
			// 遍历集合，通知所有的观察者
			for (Observer observer : mObserverList) {
				observer.update(msg);
			}
		}
	}

	public static void main(String[] args) {
		// 初始化具体的被观察者
		ConcreteSubject subject = new ConcreteSubject();

		// 创建观察者
		ConcreteObserver ob1 = new ConcreteObserver("张三");
		ConcreteObserver ob2 = new ConcreteObserver("李四");
		ConcreteObserver ob3 = new ConcreteObserver("王五");

		// 绑定观察者和被观察者
		subject.attach(ob1);
		subject.attach(ob2);
		subject.attach(ob3);

		// 被观察者发消息通知观察者
		subject.notify("订阅成功了");
	}
}
